package com.aloda.manager;

import com.aloda.constant.ExceptionConstant;
import com.aloda.exception.BaseException;
import com.aloda.properties.CosProperties;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 腾讯云上传工具类
 */
@Slf4j
@Component
public class CosManager {

    @Resource
    private COSClient cosClient;

    @Resource
    private CosProperties cosProperties;

    /**
     *
     * @param file 文件
     * @return 返回文件的浏览全路径
     */
    public String upLoadFile(MultipartFile file) {
        try {
            // 获取上传的文件的输入流
            InputStream inputStream = file.getInputStream();

            // 获取当前时间戳并格式化
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
            String timestamp = now.format(formatter);

            // 生成一个唯一的文件名以避免冲突
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || originalFilename.isEmpty()) {
                throw new IllegalArgumentException("文件名错误");
            }
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = timestamp + "_" + UUID.randomUUID().toString() + fileExtension;

            // 指定文件上传到 COS 上的路径，即对象键。最终文件会传到存储桶名字中的images文件夹下的fileName名字
            String key = cosProperties.getFileCatalog() + fileName;
            // 创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            // - 使用输入流存储，需要设置请求长度
            objectMetadata.setContentLength(inputStream.available());
            // - 设置缓存
            objectMetadata.setCacheControl("no-cache");
            // - 设置Content-Type
            objectMetadata.setContentType(fileExtension);
            //上传文件
            cosClient.putObject(cosProperties.getBucket(), key, inputStream, objectMetadata);
            // 创建文件的网络访问路径
            return cosProperties.getHost() + "/" + key;
        } catch (Exception e) {
            log.info("上传文件失败", e);
            throw new BaseException(ExceptionConstant.UPLOAD_ABNORMAL);
        }
    }

}
